<template>
  <a-layout class="main-layout">
    <TopBar></TopBar>
    <Header></Header>
    <!-- <Navigation></Navigation> -->
    
    <div id="main" class="container">
      <a-layout-content class="content">
        <!-- 根据路由决定显示内容 -->
        <template v-if="isUserRoute">

          <!-- 用户中心响应式布局 -->
          <div class="user-layout">
            <!-- 左侧边栏/顶部菜单 (在小屏幕上转为水平菜单) -->
            <aside class="user-sidebar">
              <a-menu :mode="isMobileView ? 'horizontal' : 'inline'" :selectedKeys="[activeUserMenu]"
                @select="handleUserMenuSelect" style="height: 100%;">
                <a-menu-item key="profile">
                  <template #icon>
                    <UserOutlined style="font-size: 16px;"/>
                  </template>
                  <span>Personal Data</span>
                </a-menu-item>
                <a-menu-item key="address">
                  <template #icon>
                    <EnvironmentOutlined style="font-size: 16px;"/>
                  </template>
                  <span>My Address</span>
                </a-menu-item>
                <a-menu-item key="orders">
                  <template #icon>
                    <ShoppingOutlined style="font-size: 16px;"/>
                  </template>
                  <span>My Orders</span>
                </a-menu-item>
                <a-menu-item key="cart">
                  <template #icon>
                    <ShoppingCartOutlined style="font-size: 16px;"/>
                  </template>
                  <span>My Cart</span>
                </a-menu-item>
                <a-menu-item key="wishlist">
                  <template #icon>
                    <StarOutlined style="font-size: 16px;"/>
                  </template>
                  <span>My Collection</span>
                </a-menu-item>
                <a-menu-item key="history">
                  <template #icon>
                    <HistoryOutlined style="font-size: 16px;"/>
                  </template>
                  <span>My Browsing</span>
                </a-menu-item>
                <a-menu-item key="points">
                  <template #icon>
                    <GiftOutlined style="font-size: 16px;"/>
                  </template>
                  <span>My Points</span>
                </a-menu-item>
                <a-menu-item key="coupons">
                  <template #icon>
                    <GiftOutlined style="font-size: 16px;"/>
                  </template>
                  <span>My Coupons</span>
                </a-menu-item>
                <a-menu-item key="message">
                  <template #icon>
                    <BellOutlined style="font-size: 16px;"/>
                  </template>
                  <span>My Message</span>
                </a-menu-item>
                <!-- <a-menu-item key="settings">
                  <template #icon>
                    <SettingOutlined />
                  </template>
                  <span>Account Settings</span>
                </a-menu-item> -->
              </a-menu>
            </aside>

            <!-- 右侧/下方内容区 -->
            <div class="user-main">
              <!-- 标签页导航 -->
              <a-tabs v-model:activeKey="activeTabKey" type="editable-card" @edit="onTabEdit" @change="handleTabChange">
                <a-tab-pane v-for="tab in tabs" :key="tab.key" :tab="tab.title" :closable="tab.closable" />
              </a-tabs>

              <!-- 用户中心内容 -->
              <div class="tab-content">
                <router-view />
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <!-- 常规内容布局 -->
          <router-view></router-view>
        </template>
      </a-layout-content>
      <a-layout-footer class="footer">
        <Footer></Footer>
      </a-layout-footer>
    </div>

  </a-layout>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, computed, onBeforeMount, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter, useRoute } from 'vue-router';
import TopBar from './TopBar.vue'
import Header from './Header.vue'
// import Navigation from './Navigation.vue'

import type { NavMenuItem } from './Navigation/types'
import { EnvironmentOutlined, UserOutlined, ShoppingOutlined, ShoppingCartOutlined, StarOutlined, HistoryOutlined, GiftOutlined, BellOutlined, SettingOutlined } from '@ant-design/icons-vue';
import Footer from './footer.vue'
const { locale } = useI18n();
import { getGoodsClassify } from '@/api/goods'
import { Session } from "@/utils/storage"

const router = useRouter();
const route = useRoute();
const navigationData = ref([])

const isMobile = ref(false)
const navStatus = computed(() => {
  if(window.location.pathname === '/home/index.html' || window.location.pathname === '/'){
    return '0'
  }else{
    return '75px'
  }
})

const getList = async () => {
  // 先获取缓存数据
  const cachedTabs = Session.get('navigationData')
  if (cachedTabs) {
    navigationData.value = cachedTabs
  } else {
    if (window && (window as any).__INITIAL_INDEX__ && (window as any).__INITIAL_INDEX__.classify) {
      navigationData.value = (window as any).__INITIAL_INDEX__.classify;
      console.log((window as any).__INITIAL_INDEX__,"009")
      // 存入缓存
      Session.set('navigationData', navigationData.value)
    }
  }

  // const res = await getGoodsClassify()
// if (res.code === 200) {
//   navigationData.value = res.result
// }
}
getList()
// 检查是否为移动设备
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

// 用户中心相关逻辑 - 新增部分
// 判断当前是否在用户中心路由
const isUserRoute = computed(() => {
  return route.path.startsWith('/user');
});

// 用户中心侧边栏菜单选中项
const activeUserMenu = computed(() => {
  const path = route.path;
  if (path.includes('/user/orders')) return 'orders';
  if (path.includes('/user/settings')) return 'settings';
  if (path.includes('/user/wishlist')) return 'wishlist';
  if (path.includes('/user/history')) return 'history';
  if (path.includes('/user/address')) return 'address';
  if (path.includes('/user/cart')) return 'cart';
  if (path.includes('/user/points')) return 'points';
  if (path.includes('/user/message')) return 'message';
  if (path.includes('/user/coupons')) return 'coupons';

  return 'profile';
});

// 标签页管理
const tabs = ref([
  { key: 'profile', title: 'Personal Data', closable: false, path: '/user/profile' }
]);
const activeTabKey = ref('profile');

// 监听路由变化，更新标签页
watch(() => route.path, (newPath) => {
  if (isUserRoute.value) {
    // 确定当前路由对应的菜单键
    let currentKey = 'profile';
    if (newPath.includes('/user/orders')) currentKey = 'orders';
    if (newPath.includes('/user/settings')) currentKey = 'settings';
    if (newPath.includes('/user/wishlist')) currentKey = 'wishlist';
    if (newPath.includes('/user/address')) currentKey = 'address';
    if (newPath.includes('/user/history')) currentKey = 'history';
    if (newPath.includes('/user/cart')) currentKey = 'cart';
    if (newPath.includes('/user/points')) currentKey = 'points';
    if (newPath.includes('/user/coupons')) currentKey = 'coupons';
    if (newPath.includes('/user/message')) currentKey = 'message';

    // 检查标签是否已存在
    const existingTab = tabs.value.find(tab => tab.key === currentKey);
    if (!existingTab) {
      // 添加新标签
      const title = currentKey === 'orders' ? 'My Orders' :
        currentKey === 'settings' ? 'Account Settings' :
          currentKey === 'wishlist' ? 'My Collection' :
            currentKey === 'address' ? 'My Address' :
              currentKey === 'history' ? 'My Browsing' :
                currentKey === 'cart' ? 'My Cart' :
                  currentKey === 'points' ? 'My Points' :
                    currentKey === 'coupons' ? 'My Coupons' :
                      currentKey === 'message' ? 'My Message' : 'Personal Data';

      tabs.value.push({
        key: currentKey,
        title: title,
        closable: currentKey !== 'profile', // 个人资料标签不允许关闭
        path: `/user/${currentKey}`
      });
    }

    // 更新激活的标签
    activeTabKey.value = currentKey;
  }
}, { immediate: true });

// 处理用户菜单选择
function handleUserMenuSelect({ key }) {
  router.push(`/user/${key}`);
}

// 标签页切换
function handleTabChange(key) {
  const tab = tabs.value.find(t => t.key === key);
  if (tab) {
    router.push(tab.path);
  }
}

// 标签页关闭
function onTabEdit(targetKey, action) {
  if (action === 'remove') {
    removeTab(targetKey);
  }
}

// 关闭标签
function removeTab(targetKey) {
  const targetIndex = tabs.value.findIndex(tab => tab.key === targetKey);
  if (targetIndex === -1) return;

  // 如果关闭的是当前激活的标签页，需要激活其他标签页
  if (activeTabKey.value === targetKey) {
    // 默认激活左侧标签，如果没有左侧标签则激活右侧标签
    const newActiveKey = tabs.value[targetIndex - 1]?.key || tabs.value[targetIndex + 1]?.key;

    if (newActiveKey) {
      activeTabKey.value = newActiveKey;
      const tab = tabs.value.find(t => t.key === newActiveKey);
      if (tab && tab.path) {
        router.push(tab.path);
      }
    }
  }

  // 移除标签
  tabs.value = tabs.value.filter(tab => tab.key !== targetKey);
}

// 响应式布局控制
const isMobileView = ref(false);
const windowWidth = ref(window.innerWidth);

// 监听窗口大小变化
const handleResize = () => {
  windowWidth.value = window.innerWidth;
  isMobileView.value = windowWidth.value < 1280; // 更新断点为1280px
};

onBeforeMount(() => {
  handleResize();
  window.addEventListener('resize', handleResize);
});

onMounted(() => {
  checkMobile()
  window.addEventListener('resize', checkMobile)


})

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile)
})
</script>

<style lang="scss" scoped>
$--header-height: 70px;

.main-layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background-color: #fff;
}

.container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  scroll-padding-top: $--header-height; /* Add scroll padding for the sticky header */
  margin-top: v-bind(navStatus); /* Add margin-top for the sticky header */
}

.content {
  flex: 1;
  background: #fff;
  scroll-margin-top: $--header-height; /* Ensure anchor links account for the sticky header */

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;

    &:hover {
      background: #666;
    }
  }
}

.footer {
  text-align: center;
  background: #fff;
  padding: 24px 50px;
  width: 100%;
  flex-shrink: 0;
}

.ant-dropdown-link {
  color: inherit;
}

/* Dark theme styles */
:global(.dark) {

  .header,
  .footer {
    background: #001529;
    color: rgba(255, 255, 255, 0.85);
  }

  .content {
    background: #141414;
  }
}

// 全局滚动条样式
:deep(*) {
  scrollbar-width: thin;
  -ms-overflow-style: -ms-autohiding-scrollbar;

  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;

    &:hover {
      background: #666;
    }
  }
}

.footer {
  text-align: center;
  background: #fff;
  padding: 0px;
  width: 100%;
  flex-shrink: 0;
}

:deep(.ant-layout .ant-layout-footer) {
  padding: 0px;
  color: rgba(0, 0, 0, 0.88);
  font-size: 14px;
  background: #f5f5f5;
}

// 用户中心布局样式 - 响应式布局
.user-layout {
  display: flex;
  margin: 0 auto;
  padding: 16px 8px;
  max-width: 1700px;
  min-height: calc(100vh - $--header-height - 97px);
  position: relative;

  // 小屏幕时改为垂直布局
  @media (max-width: 1280px) {
    flex-direction: column;
  }
}

.user-sidebar {
  width: 220px;
  /* 增加一点宽度 */
  background: #fff;
  // border-right: 1px solid #f0f0f0;
  overflow-y: auto;
  border-radius: 4px;
  margin-right: 60px;
  // box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 增强阴影效果 */
  position: fixed;
  // left: calc((100% - 1700px) / 2 + 8px);
  /* 居中定位 */
  top: 137px;
  max-height: calc(100vh - 130px);
  z-index: 500;
  padding: 10px;
  padding-right: 0px;
  // box-shadow: 0 0 10px 2px rgba(0, 0, 0, 0.1);

  // 小屏幕样式
  @media (max-width: 1280px) {
    position: static;
    width: 100%;
    margin-right: 0;
    margin-bottom: 16px;
    max-height: none;

    :deep(.ant-menu-horizontal) {
      border-bottom: none;
      white-space: nowrap;
      overflow-x: auto;

      &::-webkit-scrollbar {
        height: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 4px;
      }
    }
  }
}

.user-main {
  flex: 1;
  padding: 0;
  // background: #f5f5f5;
  overflow: visible;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 2;
  margin-left: 245px;
  margin-top: 32px;
  /* 调整为与侧边栏宽度相匹配 */
  box-shadow: 0 1px 10px rgba(0, 0, 0, 0.1);

  // 小屏幕样式
  @media (max-width: 1280px) {
    width: 100%;
    margin-left: 0;
  }

  :deep(.ant-tabs) {
    padding: 12px 16px 0;
    position: relative;
    z-index: 1;
  }
}

.tab-content {
  background: #fff;
  padding: 16px;
  margin-top: 8px;
  border-radius: 4px;
  min-height: 300px;
  // box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  width: 100%;
  box-sizing: border-box;
  position: relative;
  z-index: 1;
  /* 确保z-index比侧边栏低 */
}

/* Dark theme styles */
:global(.dark) {
  .user-sidebar {
    background: #001529;
    border-right-color: #303030;
  }

  .tab-content {
    background: #1f1f1f;
  }
}

/* 移除冲突的菜单样式 */
:deep(.ant-menu) {
  min-height: unset;
  /* 移除最小高度限制 */
  border-right: none;
  position: relative;
  z-index: auto;
  /* 重置z-index */
  width: 92%;
  background: transparent;

  .ant-menu-item-selected {
    background-color: transparent !important;
  }

}

:deep(.ant-menu-inline) {
  border-right: none;
}

:deep(.ant-menu-item) {
  margin: 0;
  font-size: 14px;
  margin-bottom: 8px;
  padding: 2px 0;
  border-radius: 2px;

  &:hover {
    background-color: transparent !important;

    span {
      text-decoration: underline;
    }
  }

  &.ant-menu-item-selected {
    background-color: transparent !important;
    font-size: 16px;
    color: #000;
    
    span {
      text-decoration: none;
      font-weight: bold !important;
    }
  }
}


@media (max-width: 1280px) {
  :deep(.ant-menu) {
    min-height: auto;
  }
}

</style>